package com.wxg.httpclient;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wxg.service.EnglishWordService;
import com.wxg.util.ResUtil;

public class ObtainAudioFromBaiduFanyi {
	
	/**
	 * "user.dir"得出项目的根目录
	 */
	public static final String USER_DIR = System.getProperty("user.dir");

	private static final Logger log = LoggerFactory.getLogger(ObtainAudioFromBaiduFanyi.class);
	
//	private static final String FILE_PATH_PREFIX = "C:\\Users\\pactera\\Desktop\\444\\";
	private static String FILE_PATH_PREFIX = null;
	
	static {
		FILE_PATH_PREFIX = ResUtil.val("AudioPath");
	}

	public static enum AudioType{
		USA("en"), 
		Britain("uk");
		
		private String lan; //en:美音, uk:英音
		private AudioType(String lan){this.lan=lan;}
		public String getLan() {
			return lan;
		}
		
	}
	
	
	public static void main(String[] args) {
		test2();
	}
	
	public static void test2(){
		queryWord("world", AudioType.USA);
		queryWord("world", AudioType.Britain);
	}
	
	public static void test1(){
		String tpl = "{1}_{2}.mp3";
		System.out.println( tpl.replace("{1}", "aa").replace("{2}", "bb") );
	}
	
	public static void test0(){
		String filepath = "C:\\Users\\pactera\\Desktop\\444\\hello.mp3";
		String url = "http://fanyi.baidu.com/gettts?lan=en&text=hello&spd=3&source=web";
		byte[] byteBuf = obtainExplainFromYoudao(url);
		exportByteArrToFile(filepath, byteBuf);
	}
	
	/**
	 * 
	 * @param word
	 * @param type
	 * @return mp3文件的地址
	 */
	public static String queryWord(String word, AudioType type){
		String tpl0 = FILE_PATH_PREFIX + "{1}_{2}.mp3";
		String path = tpl0.replace("{1}", word).replace("{2}", type.getLan());
		
		//感觉没必要查询sqlite数据库啊!!!
//		EnglishWordService service = new EnglishWordService();
//		Englishword ew = service.findByWord(word);
//		if(null != ew){
//			String usapath = ew.getUsaPath();
//			String britainpath = ew.getBritainPath();
//			if( (AudioType.USA.equals(type) && StringUtils.isNotBlank(usapath)) 
//					|| (AudioType.Britain.equals(type) && StringUtils.isNotBlank(britainpath)) ){
//				System.out.println(String.format("===[%s]已经存在！===", path));
//			}else{
//				byte[] byteBuf = obtainExplainFromYoudao(url);
//				exportByteArrToFile(path, byteBuf);
//				System.out.println(String.format("===[%s]从服务器下载！===", url));
//			}
//		}
		
		File file = new File(path);
		if(file.exists()){
			if(log.isDebugEnabled()){
				log.debug(String.format("===[%s]已经存在！===", path));
			}
		}else{
			String tpl2 = "http://fanyi.baidu.com/gettts?lan={2}&text={1}&spd=3&source=web";
			String url = tpl2.replace("{1}", word).replace("{2}", type.getLan());
			
			byte[] byteBuf = obtainExplainFromYoudao(url);
			exportByteArrToFile(path, byteBuf);
			if(log.isInfoEnabled()){
				log.info(String.format("===[%s]从服务器下载！===", url));
			}
			
			// 应该在这里存储, 而不是在外面!
			EnglishWordService service = new EnglishWordService();
//			service.addWord(word);
			service.addWord(word, path, type);
		}
		return path;
	}
	
	public static void exportByteArrToFile(String filepath, byte[] byteBuf){
		BufferedOutputStream bos = null;
		try {
			try {
				bos = new BufferedOutputStream(new FileOutputStream(new File(filepath)));
				bos.write(byteBuf);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}finally{
				if(null != bos){
					bos.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static byte[] obtainExplainFromYoudao(String url){
		byte[] result = null;
		CloseableHttpClient httpclient = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-type", "audio/x-mpeg");
			httpPost.setHeader("Accept", "audio/x-mpeg");
			CloseableHttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toByteArray(entity);
			}
			httpclient.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return result;
	}
}
